package zmzsapplet

import (
	"fmt"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
	"github.com/gin-gonic/gin"
	"github.com/gogap/logs"
	"github.com/shopspring/decimal"
	"go.uber.org/zap"
	"log"
	"strconv"
	"time"
	"yundian/internel/app/dao"
	"yundian/internel/app/dao/memberdao"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/logic"
	"yundian/internel/app/models/devices"
	"yundian/internel/app/models/devploys"
	"yundian/internel/app/models/devrule"
	"yundian/internel/app/models/liveservicelog"
	"yundian/internel/app/models/membermodel"
	"yundian/internel/app/models/placemodel"
	"yundian/internel/app/models/ploys"
	"yundian/internel/app/models/prices"
	"yundian/internel/app/models/room"
	"yundian/internel/app/models/users"
	"yundian/internel/app/models/wifimodel"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
	. "yundian/internel/pkg/dingo/result"
	"yundian/internel/pkg/utils"
)

// HandleWxLoginWifi 微信小程序登录 - 中曼助手
func HandleWxLoginWifi(ctx *gin.Context) {
	param := &struct {
		Code string `form:"code" binding:"required"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	respData, err := payClient.Login(param.Code, "wxa2d02c6a1e8ffb24", "9cf987e94d3733e3bc46990993cff5e3")
	if err != nil {
		zap.L().Error(err.Error())
		Response(ctx)(err.Error(), CodeError, nil)(Error)
		return
	}

	// 处理业务逻辑
	loginResult, err := logic.NewWxAuthLogic().HandleLogicLoginWifi(respData, "wxa2d02c6a1e8ffb24")
	if err != nil {
		zap.L().Error(err.Error())
		Response(ctx)(err.Error(), CodeError, nil)(Error)
		return
	}

	// 响应给前端
	loginResult.Host = global.Cfg.Ali.AliossPath
	Response(ctx)("", CodeSuccess, loginResult)(OK)
}

// HandleWxLoginOutWifi 退出登录
func HandleWxLoginOutWifi(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		dingo.ErrorIf(err).Unwrap()
	}
	key := utils.Join(global.Const.Pre.TokenKeyPre, "-Wifi-Applet-Login-Token", strconv.Itoa(userId))
	// 清除redis缓存中的token
	global.Rdb.Del(ctx, key)
	Response(ctx)("成功退出", CodeSuccess, true)(OK)
}

// HandleInsertWifiServiceLog 新增服务日志 - WIFI引流
func HandleInsertWifiServiceLog(ctx *gin.Context) {
	userId, _ := helper.GetUserIdFromCtx(ctx)
	openid, _ := helper.GetUserNameFromCtx(ctx)

	param := &request.LiveServiceInsertReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	m := &liveservicelog.LiveServiceLogModel{}
	//获取设备信息
	devInfo := dao.NewDeviceDao().GetDeviceInfoWithPlace(param.DeviceSn).Unwrap().(*devices.DeviceWithPlace)
	m.PlaceId = devInfo.PlaceId
	m.PlaceName = devInfo.PlaceName
	m.ClientIp = ctx.ClientIP()
	m.CreateAt = dingo.Time(time.Now().Unix())
	m.DeviceSn = param.DeviceSn
	m.Openid = openid
	m.MemberId = userId
	m.Appid = param.AppId
	m.ServiceType = param.ServiceType
	m.ServiceDesc = param.ServiceDesc

	Response(ctx)("", CodeInsertSuccess, dao.NewLiveServiceLogDao().InsertWifiLiveServiceLog(m).Unwrap())(OK)
}

// HandleComputeAdIncome 广告收益算法
func HandleComputeAdIncome(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	openid, err := helper.GetUserNameFromCtx(ctx)
	if err != nil {
		dingo.ErrorIf(err).Unwrap()
	}

	param := &request.AdIncomeReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	if param.OpenId == "" || param.DeviceSn == "" || param.PlaceId == 0 || param.Appid == "" {
		Response(ctx)("", CodeInsertSuccess, 0)(OK)
		return
	}
	if userId <= 0 {
		Response(ctx)("", CodeInsertSuccess, 0)(OK)
		return
	}
	if param.OpenId != openid {
		Response(ctx)("", CodeInsertSuccess, 0)(OK)
		return
	}
	if param.Appid != "wxa2d02c6a1e8ffb24" {
		Response(ctx)("", CodeInsertSuccess, 0)(OK)
		return
	}

	// 1、计算广告收益
	adIncome := logic.NewWifiLogic().AdIncomeCompute(param)
	// 广告最大值不能大于0.5
	if adIncome >= 0.50 {
		adIncome = 0.30
	}

	// 2、判断用户当天点击是否产生过收益
	tradeNo := utils.Join(global.Const.Pre.OrderPre, time.Now().Format("20060102150405"), utils.GetRandomInt(6))
	dateStr := time.Now().Format("2006-01-02")                                                   // 当天时间
	deviceInfo := dao.NewOrderDao().GetDeviceInfo(param.DeviceSn).Unwrap().(*devices.DeviceType) // 获取设备信息
	// 设备不存在
	if deviceInfo.ID <= 0 {
		Response(ctx)("", CodeInsertSuccess, 0)(OK)
		return
	}
	userInfo := dao.NewUserDao().GetUserInfoByPlaceId(param.PlaceId).Unwrap().(*users.UserModel) // 获取用户信息
	if userInfo.ID <= 0 {
		Response(ctx)("门店未绑定用户", CodeInsertSuccess, 0)(OK)
		return
	}
	wifiUserInfo := memberdao.NewMemberDao().GetWifiUserInfoByUserId(userInfo.ID).Unwrap().(*users.WifiUserDetail)

	// 当一个用户的一天收益达到10元时发送短信通知
	incomeTotal := dao.NewWifiDao().GetWifiUserIncomeByDateStr(userInfo.ID).Unwrap().(*wifimodel.AdIncomeList)
	if incomeTotal.AdPrice >= 50.0 {
		// 验证此用户收益达到阀值时发送短信
		client, _ := dysmsapi.NewClientWithAccessKey(global.Cfg.Ali.AccessRegionid, global.Cfg.Ali.AccessKey, global.Cfg.Ali.AccessKeySecret)
		request := dysmsapi.CreateSendSmsRequest()
		request.Method = "POST"                               // 设置请求方式
		request.Scheme = "https"                              // https | http
		request.QueryParams["PhoneNumbers"] = "17602184021"     //手机号
		request.QueryParams["SignName"] = "中曼物联"              //阿里云验证过的项目名 自己设置
		request.QueryParams["TemplateCode"] = "SMS_218615274" //阿里云的短信模板号 自己设置
		request.QueryParams["TemplateParam"] = "{\"code\":" + param.DeviceSn + "}"
		//request属性设置
		_, _ = client.SendSms(request)
	}

	// 3、创建订单、收益分红
	logs.Info("打印测试----", param.OpenId, param.Appid, dateStr, tradeNo, adIncome, param.DeviceSn, param.PlaceId)
	c := dao.NewWifiDao().CountAdOrder(dateStr, param.OpenId, param.Appid).Unwrap().(int64)
	if c == 0 {
		logic.NewWifiLogic().AddIncome(tradeNo, adIncome, wifiUserInfo, deviceInfo, param, ctx.ClientIP()) // 收益分成
	}

	Response(ctx)("", CodeInsertSuccess, adIncome)(OK)
}

// HandleGetTeamCount 获取团队数量
func HandleGetTeamCount(ctx *gin.Context) {
	useId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()
	userInfo := memberdao.NewMemberDao().GetWifiUserInfoByMemberId(useId).Unwrap().(*users.WifiUserDetail)

	// 团队总数、拓展员数、商户数
	teamCount := dao.NewWifiDao().GetUserCountByParentId(userInfo.UserId, 0).Unwrap().(int64)
	bdCount := dao.NewWifiDao().GetUserCountByParentId(userInfo.UserId, 9).Unwrap().(int64)
	placeCount := dao.NewWifiDao().GetUserCountByParentId(userInfo.UserId, 3).Unwrap().(int64)

	Response(ctx)("", CodeSuccess, &struct {
		TeamCount  int64 `json:"teamCount"`
		BdCount    int64 `json:"bdCount"`
		PlaceCount int64 `json:"placeCount"`
	}{
		TeamCount:  teamCount,
		BdCount:    bdCount,
		PlaceCount: placeCount,
	})(OK)
}

// HandleGetTeamList 获取团队列表
func HandleGetTeamList(ctx *gin.Context) {
	useId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()
	userInfo := memberdao.NewMemberDao().GetWifiUserInfoByMemberId(useId).Unwrap().(*users.WifiUserDetail)
	// 请求参数处理
	param := &request.BaseListReq{}
	//param := &request.UserList{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	data := dao.NewWifiDao().GetUserListByParentId(userInfo.UserId, param, "wifi")

	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: 0,
		TotalPage:  0,
		Data:       data.Unwrap(),
	})(OK)
	// 获取所有下级
	//param.ParentId = userInfo.UserId
	//logs.Info("用户ID", userInfo.UserId)
	//if userInfo.UserId > 0 {
	//	data := dao.NewUserDao().GetUserListByIsAdmin(param)
	//	lists := data.Unwrap().([]*users.UserInfoWithAgent)
	//	logic.NewUserLogic().FindAllIsAdminUserListBatch(&lists, param.IsAdmin, 0)
	//	Response(ctx)("", CodeSuccess, ResponseList{
	//		PageNo:     param.PageNo,
	//		PageSize:   param.PageSize,
	//		TotalCount: data.Val().(int64),
	//		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
	//		Data:       lists,
	//	})(OK)
	//	return
	//}
	//
	//Response(ctx)("", CodeSuccess, ResponseList{
	//	PageNo:     param.PageNo,
	//	PageSize:   param.PageSize,
	//	TotalCount: 0,
	//	TotalPage:  0,
	//	Data:       nil,
	//})(OK)
}

// HandleGetBdList 获取BD列表
func HandleGetBdList(ctx *gin.Context) {
	useId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()
	userInfo := memberdao.NewMemberDao().GetWifiUserInfoByMemberId(useId).Unwrap().(*users.WifiUserDetail)
	// 请求参数处理
	//param := &request.BaseListReq{}
	param := &request.UserList{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	data := dao.NewWifiDao().GetUserListByParentIdAndIsAdmin(userInfo.UserId, helper.TypeNumIsAdminBd, param)


	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       data.Unwrap(),
	})(OK)
}

// HandleGetWifiUserInfo 获取用户信息
func HandleGetWifiUserInfo(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		dingo.ErrorIf(err).Unwrap()
	}
	memInfo := memberdao.NewMemberDao().GetMemberInfoById(userId).Unwrap().(*membermodel.MembersModel)
	//userInfo := dao.NewUserDao().GetUserInfoByPhone(memInfo.Phone).Unwrap().(*users.UserModel)
	userInfo := memberdao.NewMemberDao().GetWifiUserInfoByMemberId(memInfo.ID).Unwrap().(*users.WifiUserDetail)
	//log.Println("打印测试用户登录信息", userInfo)
	// 响应请求
	Response(ctx)("", CodeSuccess, userInfo)(OK)
}

// HandleGetWifiUserInfoById 获取用户信息
func HandleGetWifiUserInfoById(ctx *gin.Context) {
	param := &struct {
		UserId int `form:"userId" json:"userId"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	userInfo := memberdao.NewMemberDao().GetWifiUserInfoByUserId(param.UserId).Unwrap().(*users.WifiUserDetail)

	Response(ctx)("", CodeSuccess, userInfo)(OK)
}

func HandleGetWifiAdCashMoney(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()
	userInfo := memberdao.NewMemberDao().GetWifiUserInfoByMemberId(userId).Unwrap().(*users.WifiUserDetail)

	// 计算已提现金额(处理成功的)
	cashTotal := dao.NewWifiDao().GetCashLogByUserId(userInfo.UserId).Unwrap().(int64)
	log.Println("打印测试数据--已提现金额", cashTotal)

	// 计算分红总金额
	dividTotal := dao.NewWifiDao().GetDividendsMoneyByUserId(userInfo.UserId).Unwrap().(float64)
	log.Println("打印测试数据--分红总金额", dividTotal)

	// 计算帐期 15天
	dateStr := time.Now().AddDate(0, 0, -7).Format("2006-01-02")
	unCashMoney := dao.NewWifiDao().GetUnCashMoneyByUserId(userInfo.UserId, dateStr).Unwrap().(float64) // 未入帐金额
	cashMoney := dao.NewWifiDao().GetCashMoneyByUserId(userInfo.UserId, dateStr).Unwrap().(float64)     // 已入帐金额
	log.Println("打印测试数据--未入帐，已入帐金额", unCashMoney, cashMoney)

	// 可提现金额 = 已入帐金额 - 已提现金额
	withdrawalMoney, _ := decimal.NewFromFloat(cashMoney).Sub(decimal.NewFromInt(cashTotal).Div(decimal.NewFromInt(100))).Float64()
	log.Println("打印测试数据--可提现金额", withdrawalMoney)

	// 可提现金额 = 分红总金额 - 已提现金额
	Response(ctx)("", CodeSuccess, &struct {
		CashTotal       string `json:"cashTotal"`       // 已提现金额
		DividTotal      string `json:"dividTotal"`      // 分红总额
		UnCashMoney     string `json:"unCashMoney"`     // 未入帐
		CashMoney       string `json:"cashMoney"`       // 已入帐
		WithdrawalMoney string `json:"withdrawalMoney"` // 可提现
	}{
		CashTotal:       decimal.NewFromInt(cashTotal).Div(decimal.NewFromFloat(100)).StringFixed(2),
		DividTotal:      decimal.NewFromFloat(dividTotal).StringFixed(2),
		UnCashMoney:     decimal.NewFromFloat(unCashMoney).StringFixed(2),
		CashMoney:       decimal.NewFromFloat(cashMoney).StringFixed(2),
		WithdrawalMoney: decimal.NewFromFloat(withdrawalMoney).StringFixed(2),
	})(OK)
}

// 获取提现记录
func HandleGetWifiAdCashList(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()
	param := &request.CashListReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	param.UserId = userId

	data := dao.NewWifiDao().GetCashList(param)

	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       data.Unwrap(),
	})(OK)
}

// 获取收益明细
func HandleGetWifiAdIncomeList(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &request.IncomeListReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param))

	userInfo := memberdao.NewMemberDao().GetWifiUserInfoByMemberId(userId).Unwrap().(*users.WifiUserDetail)
	param.UserId = userInfo.UserId

	data := dao.NewWifiDao().GetIncomeList(param)

	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       data.Unwrap(),
	})(OK)
}

func HandleGetWifiAdCashRecord(c *gin.Context) {

	userId, err := helper.GetUserIdFromCtx(c)
	if err != nil {
		Response(c)(err.Error(), CodeNeedLogin, false)(Unauthorized)
		return
	}
	//判断是否存在未处理的订单
	cashLogInfo := dao.NewWifiDao().GetCashLogByInfo(userId).Unwrap().(wifimodel.AdCashLogModel)
	Response(c)("", CodeSuccess, cashLogInfo)(OK)
}

func HandleGetWithdrawalSettingInfo(c *gin.Context) {

	param := &request.AdminUserInsertReq{}
	dingo.ErrorIf(c.Bind(param)).Unwrap()
	Response(c)("", CodeUpdateSuccess,
		dao.NewCashDao().GetWithdrawalSettingInfo(3).Unwrap())(OK)
}

//获取省市县
func HandleGetRegions(ctx *gin.Context) {
	param := &struct {
		RegionsId int `form:"regionsId"`
		Level     int `form:"level"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	Response(ctx)("", CodeSuccess, dao.NewPlaceDao().GetRegionsByLevel(param.Level).Unwrap())(OK)
}

//获取省市县
func HandleGetRegionsByParent(ctx *gin.Context) {
	param := &struct {
		Parent int `form:"parent"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()

	Response(ctx)("", CodeSuccess, dao.NewPlaceDao().GetRegionsListByParent(param.Parent).Unwrap())(OK)
}

// InsertPlace 新增网点信息API
func HandleInsertPlace(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()
	userName, _ := helper.GetUserNameFromCtx(ctx)

	param := &request.PlaceInsertReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	//查询网点名称是否重复
	_, isRepeat := dao.NewPlaceDao().GetPlaceNameIsRepeat(param.PlaceName)
	if isRepeat > 0 {
		Response(ctx)("该网点名称已被使用", CodeError, false)(OK)
		return
	}

	placeInfo := dao.NewUserDao().InsertPlaceInfo(param).Unwrap().(*placemodel.PlaceModel)

	ruleInfos := dao.NewPricesDao().GetDeviceRuleInfoList().Unwrap().([]devrule.DeviceRulesModel)

	//查询商户奖励规则
	ploysInfo := dao.NewPricesDao().GetDevicePloysInfoList().Unwrap().([]devploys.DevicePloysModel)

	// 新增商户计费规则
	for _, ruleInfo := range ruleInfos {
		m := prices.New()
		m.DeviceTypeId = ruleInfo.TypeId
		m.PlaceId = placeInfo.Id
		m.Status = ruleInfo.Status
		m.ProductId = utils.Str2Md5(helper.GenerateUUID())

		// -----套餐模式 开始------
		m.UseDuration = ruleInfo.UseDuration // 使用时长
		m.PayMoney = ruleInfo.PayMoney       // 支付金额-单位分
		m.SetMealNum = ruleInfo.SetMealNum   // 规则序号
		m.RuleName = ruleInfo.RuleName       // 规则名
		m.IsRecommend = ruleInfo.IsRecommend // 是否推荐
		m.Priority = ruleInfo.Priority       // 排序
		// -----套餐模式 结束------

		// -----计时模式 开始------
		m.MaxPayPrice = ruleInfo.MaxPayPrice           // 日封顶价格
		m.PayIntervalPrice = ruleInfo.PayIntervalPrice // 每60分钟支付2元
		m.PayInterval = int(ruleInfo.PayInterval)      // 每60分钟支付2元
		m.MaxTime = ruleInfo.MaxTime                   // 最大使用时长
		m.BasePrice = ruleInfo.BasePrice               // 最低使用价格
		m.BaseTimes = int(ruleInfo.BaseTimes)          // 最低使用时长
		m.FreeTimes = int(ruleInfo.FreeTimes)          // 免费使用时长
		m.Deposit = ruleInfo.Deposit                   //  押金
		// -----计时模式 结束------
		//酒店ID

		m.CreateAt = dingo.Time(time.Now().Unix())
		dao.NewPricesDao().InsertPlacePrice(m).Unwrap() // 新增 商户价格
	}

	//新增商户奖励规则
	for _, ploysVal := range ploysInfo {
		m := ploys.New()
		m.PlaceId = placeInfo.Id
		m.PlaceName = placeInfo.PlaceName

		//
		m.Status = ploysVal.Status
		m.UserId = ploysVal.UserId
		m.Type = ploysVal.Type
		m.TypeId = ploysVal.TypeId
		m.UserName = ploysVal.UserName
		m.Num = ploysVal.Num
		m.Range = ploysVal.Range
		m.PloyType = ploysVal.PloyType
		m.PloyName = ploysVal.PlaceName
		m.SharedMode = ploysVal.SharedMode

		m.CreateAt = dingo.Time(time.Now().Unix())

		dao.NewPricesDao().InsertPloys(m).Unwrap() // 新增商户奖励规则
	}

	// 门店新增写入日志
	pol := placemodel.PlaceOperateLog{
		PlaceId:           placeInfo.Id,
		PlaceName:         placeInfo.PlaceName,
		OperationUserId:   userId,
		OperationUserName: userName,
		OperateIP:         ctx.ClientIP(),
		Description:       "门店新增",
		Remark:            "门店新增",
		CreateAt:          0,
		BeforeField:       "",
		AfterField:        "",
		PlaceDesc:         param.PlaceDesc,
		PlaceDescAfter:    param.PlaceDesc,
	}
	dingo.Task(logic.NewLogsLogic().InsertPlaceOperateLogLogic, func() {}, pol, param, placeInfo)

	//if placeInfo.Status == 4 { // 需要审核的门店
	//	dingo.Task(logic.NewShWxNotificationsLogic().WeChatGroupRobotNotificationsByPlace,
	//		func() {}, placeInfo.Id)
	//}

	Response(ctx)("", CodeInsertSuccess, placeInfo)(OK)
}

func HandleInsertPlaceImg(ctx *gin.Context) {
	param := &request.PlaceInsertReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	placeInfo := dao.NewUserDao().UpdatePlaceInfoImg(param).Unwrap().(*placemodel.PlaceModel)

	Response(ctx)("", CodeInsertSuccess, placeInfo)(OK)
}

// UpdatePlace 更新网点信息API
func HandleUpdatePlace(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	userName, _ := helper.GetUserNameFromCtx(ctx)
	isAdmin, _ := helper.GetIsAdminFromCtx(ctx)
	parentId, _ := helper.GetParentIdFromCtx(ctx)

	t := 0
	// 运营商 || 超级管理员 || 运营商下的员工
	if isAdmin == helper.TypeNumIsAdminOperator || isAdmin == helper.TypeNumIsAdminAdministrator || (isAdmin == helper.TypeNumIsAdminStaff && parentId == 2) {
		t = 1
	}

	param := &request.PlaceInsertReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	//查询网点名称是否重复
	placeModel, isRepeat := dao.NewPlaceDao().GetPlaceNameIsRepeat(param.PlaceName)
	isRepeatModel := placeModel.Unwrap().(*placemodel.PlaceModel)
	if isRepeat > 0 && param.Id != isRepeatModel.Id {
		Response(ctx)("该网点名称已被使用", CodeError, false)(OK)
		return
	}

	// 门店修改写入日志
	pInfo := dao.NewPlaceDao().GetPlaceDetailById(param.Id).Unwrap().(*placemodel.PlaceModel)
	pol := placemodel.PlaceOperateLog{
		PlaceId:           pInfo.Id,
		PlaceName:         pInfo.PlaceName,
		OperationUserId:   userId,
		OperationUserName: userName,
		OperateIP:         ctx.ClientIP(),
		Description:       "门店修改",
		Remark:            "门店修改",
		CreateAt:          0,
		BeforeField:       "",
		AfterField:        "",
		PlaceDesc:         pInfo.PlaceDesc,
		PlaceDescAfter:    param.PlaceDesc, // 修改之后
	}

	dingo.Task(logic.NewLogsLogic().InsertPlaceOperateLogLogic, func() {}, pol, param, pInfo)

	Response(ctx)("", CodeUpdateSuccess,
		dao.NewUserDao().UpdatePlaceInfo(param, t).Unwrap())(OK)
}

// 获取WIFI列表
func HandleGetDeviceList(ctx *gin.Context) {
	loginUserId, err := helper.GetUserIdFromCtx(ctx) // 获取当前登录用户ID
	dingo.ErrorIf(err).Unwrap()

	param := &request.StewardDeviceListReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	param.LoginUserId = loginUserId
	param.IsAdmin, _ = helper.GetIsAdminFromCtx(ctx)
	param.ParentId, _ = helper.GetParentIdFromCtx(ctx)

	data := dao.NewWifiDao().FetchWifiDeviceList(param)
	lists := data.Unwrap().([]*request.StewardDeviceListRes)

	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  0,
		Data:       lists,
	})(OK)
}

// HandleGetNearbyWifiList 查询附近WIFI列表
func HandleGetNearbyWifiList(ctx *gin.Context) {
	param := &request.GetNearbyWifiListReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	data := dao.NewPlaceDao().GetNearbyWifiList(param)
	Response(ctx)("", CodeSuccess, data.Unwrap())(OK)
}

// HandleSetDeviceSnWifi 设置WIFI
func HandleSetDeviceSnWifi(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()
	userInfo := memberdao.NewMemberDao().GetWifiUserInfoByMemberId(userId).Unwrap().(*users.WifiUserDetail)

	param := &request.SetStewardDeviceReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	if param.PlaceId == 0 {
		p := &request.PlaceInsertReq{}
		placeInfo := dao.NewPlaceDao().GetLastPlaceInfo().Unwrap().(*placemodel.PlaceModel)
		p.PlaceName = utils.Join(userInfo.Name, "-", strconv.Itoa(placeInfo.Id + 1))
		p.ClassName = "其它"
		p.UserId = userInfo.UserId
		p.Name = userInfo.UserName
		p.Status = 1
		info := dao.NewUserDao().InsertPlaceInfo(p).Unwrap().(*placemodel.PlaceModel)
		param.PlaceId = info.Id
	}

	// 分配二维码设备
	if param.DeviceSn == "" {
		var err error
		var userIds []int
		userInfo := &users.UserModel{}
		var userList []*users.UserModel
		if userInfo = dao.NewUserDao().GetUserByPlaceId(param.PlaceId).Unwrap().(*users.UserModel); userInfo.ID <= 0 {
			Response(ctx)("网点错误", CodeError, false)(OK)
			return
		}
		if userList, err = dao.NewUserDao().QueryParentListAll(userInfo, userList, 0); err != nil {
			fmt.Println("QueryParentListAll", err)
			Response(ctx)("网点错误", CodeInternalServerError, false)(OK)
			return
		}
		for _, item := range append(userList, userInfo) {
			if item.IsAdmin > 2 {
				userIds = append(userIds, item.ID)
			}
		}
		deviceInfo := dao.NewDeviceDao().GetDeviceByUserIds(userIds).Unwrap().(*devices.DeviceModel)
		if deviceInfo.ID > 0 {
			placeInfo := dao.NewPlaceDao().GetPlaceById(param.PlaceId).Unwrap().(*placemodel.PlaceModel)
			deviceInfo.PlaceId = param.PlaceId
			deviceInfo.PlaceName = placeInfo.PlaceName
			if err := dao.NewDeviceDao().SetStewardDeviceWifi(deviceInfo).Err; err != nil {
				Response(ctx)("创建失败", CodeError, false)(OK)
				return
			}
			param.DeviceSn = deviceInfo.DeviceSn
		} else {
			Response(ctx)("设备码己用完", CodeError, false)(OK)
			return
		}
	} else {
		deviceInfo := dao.NewDeviceDao().GetDeviceByDeviceSn(param.DeviceSn).Unwrap().(*devices.DeviceModel)
		if deviceInfo.ID == 0 {
			Response(ctx)("当前WIFI码未开放", CodeError, false)(OK)
			return
		}
		if deviceInfo.PlaceId == 0 {
			placeInfo := dao.NewPlaceDao().GetPlaceById(param.PlaceId).Unwrap().(*placemodel.PlaceModel)
			deviceInfo.PlaceId = placeInfo.Id
			deviceInfo.PlaceName = placeInfo.PlaceName
			if err := dao.NewDeviceDao().SetStewardDeviceWifi(deviceInfo).Err; err != nil {
				Response(ctx)("创建失败", CodeError, false)(OK)
				return
			}
		} else if deviceInfo.PlaceId != param.PlaceId {
			Response(ctx)("当前WIFI二维码已经绑定其它网点", CodeError, false)(OK)
			return
		}
		param.Room = deviceInfo.Room
		param.PlaceId = deviceInfo.PlaceId
	}

	// 防止重复添加房间
	if param.Room == "" {
		roomName := dao.NewRoomDaoDao().GetPlaceMaxRoom(param.PlaceId).Unwrap().(string)
		roomNum, _ := strconv.Atoi(roomName)
		param.Room = fmt.Sprintf("%d", utils.IfTrueInt(roomNum > 0, roomNum+1, 1))
	}

	if data := dao.NewDeviceDao().SetStewardDevice(param); data.Err != nil {
		Response(ctx)("", CodeInternalServerError, false)(OK)
		return
	}

	Response(ctx)("", CodeSuccess, param.DeviceSn)(OK)
}

// HandleGetUserWifiList 查询用户WIFI列表
func HandleGetUserWifiList(ctx *gin.Context) {
	param := &request.GetUserWifiListReq{}
	dingo.ErrorIf(ctx.Bind(param)).Unwrap()

	memberId, _ := helper.GetUserIdFromCtx(ctx)
	userInfo := memberdao.NewMemberDao().GetWifiUserInfoByMemberId(memberId).Unwrap().(*users.WifiUserDetail)
	param.UserId = userInfo.UserId
	param.IsAdmin = userInfo.IsAdmin

	data := dao.NewRoomDaoDao().GetUserRoomWifiList(param)
	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  0,
		Data:       data.Unwrap(),
	})(OK)
	//Response(ctx)("", CodeSuccess, data.Unwrap())(OK)
}

func HandleGetPlaceListByUserId(ctx *gin.Context) {
	//userId, err := helper.GetUserIdFromCtx(ctx)
	//dingo.ErrorIf(err).Unwrap()
	//IsAdmin, _ := helper.GetIsAdminFromCtx(ctx)
	//
	//param := &request.PlaceListByPlaceReq{}
	//dingo.ErrorIf(ctx.ShouldBindQuery(param))
	//param.UserId = userId
	//
	//placeIds := []int{}
	//data := dao.NewPlaceDao().GetPlaceListByPlace(param, IsAdmin)
	//lists := data.Unwrap().([]*placeresp.GetPlaceIdWithHotelId)
}

// HandleBindWifiWithDev 绑定WIFI列表
func HandleBindWifiWithDev(ctx *gin.Context) {
	//deviceSn: dev, placeId: item.placeId, wifiName: item.wifiName, wifiPassword: item.wifiPassword
	param := &struct {
		DeviceSn       string   `json:"deviceSn"`
		PlaceId        int      `json:"placeId"`
		WifiName       string   `json:"wifiName"`
		WifiPassword   string   `json:"wifiPassword"`
	}{}
	dingo.ErrorIf(ctx.BindJSON(param)).Unwrap()

	deviceInfo := dao.NewDeviceDao().GetDeviceByDeviceSn(param.DeviceSn).Unwrap().(*devices.DeviceModel)
	if deviceInfo.ID == 0 { // 设备不存在
		Response(ctx)("当前WIFI码未开放", CodeError, false)(OK)
		return
	}

	if deviceInfo.PlaceId == 0 { // 未绑定门店ID
		placeInfo := dao.NewPlaceDao().GetPlaceById(param.PlaceId).Unwrap().(*placemodel.PlaceModel) // 获取门店信息
		deviceInfo.PlaceId = placeInfo.Id
		deviceInfo.PlaceName = placeInfo.PlaceName
		if err := dao.NewDeviceDao().SetStewardDeviceWifi(deviceInfo).Err; err != nil { // 绑线
			Response(ctx)("创建失败", CodeError, false)(OK)
			return
		}
	} else if deviceInfo.PlaceId != param.PlaceId {
		Response(ctx)("当前WIFI二维码已经绑定其它网点", CodeError, false)(OK)
		return
	}

	wifiInfo := dao.NewRoomDaoDao().GetRoomDetailsByDeviceSn(param.DeviceSn).Unwrap().(*room.Room)
	if wifiInfo.WifiName != "" { // 此设备已配置wifi信息
		Response(ctx)("此设备已配置wifi信息", CodeError, false)(OK)
		return
	}

	m := &request.SetStewardDeviceReq{}
	m.DeviceSn = param.DeviceSn
	m.PlaceId = param.PlaceId
	m.WifiName = param.WifiName
	m.WifiPassword = param.WifiPassword
	m.Room = utils.Join(param.DeviceSn, "-", strconv.Itoa(param.PlaceId))
	if data := dao.NewDeviceDao().SetStewardDevice(m); data.Err != nil {
		Response(ctx)("设备绑定失败", CodeError, false)(OK)
		return
	}

	Response(ctx)("设备绑定成功", CodeSuccess, param.DeviceSn)(OK)

}

func HandleGetWifiPassword(ctx *gin.Context)  {
	param := &struct {
		WifiName string `json:"wifiName"`
	}{}
	data := dao.NewRoomDaoDao().GetRoomDetailsByWifiName(param.WifiName)
	if data.Err != nil {
		Response(ctx)("", CodeSuccess, false)(OK)
		return
	}
	Response(ctx)("", CodeSuccess, data.Unwrap())(OK)
}

// 提现
func HandleWifiUserWithDrawal(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	userInfo := memberdao.NewMemberDao().GetWifiUserInfoByMemberId(userId).Unwrap().(*users.WifiUserDetail)

	param := &request.WithDrawalReq{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param))

	param.UserId = userInfo.UserId
	param.ClientIp = ctx.ClientIP()

	err = logic.NewOrderLogic().HandleWifiUserTransfers(param)
	if err != nil {
		Response(ctx)(err.Error(), CodeSuccess, false)(OK)
		return
	}
	Response(ctx)("", CodeSuccess, true)(OK)
}

// 更新昵称
func HandleUpdateMemberNickName(ctx *gin.Context)  {
	memberId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	param := &struct {
		Nickname string `json:"nickname"`
		AvatarUrl string `json:"avatarUrl"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param))

	Response(ctx)("",
		CodeSuccess,
		memberdao.NewMemberDao().UpdateMemberNickName(memberId, param.Nickname, param.AvatarUrl).Unwrap())(OK)

}

// 更新Wifi用户
func HandleUpdateWifiUser(ctx *gin.Context)  {
	param := &struct {
		IsAdmin uint8 `json:"isAdmin"` // 角色
		IsDivinds uint8 `json:"isDivinds"` // 是否参与分红
		ProfitProportion int `json:"profitProportion"` // 分成
		UserId   int `json:"userId"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param))

	if param.IsAdmin != 3 && param.IsAdmin != 9 && param.IsAdmin != 8 {
		Response(ctx)("", CodeSuccess, false)(OK)
		return
	}

	userInfo := memberdao.NewMemberDao().GetWifiUserInfoByUserId(param.UserId).Unwrap().(*users.WifiUserDetail)
	parentUserInfo := memberdao.NewMemberDao().GetWifiUserInfoByUserId(userInfo.ParentId).Unwrap().(*users.WifiUserDetail)

	if param.UserId <= 0 {
		Response(ctx)("用户错误", CodeError, false)(OK)
		return
	}
	if parentUserInfo.ProfitProportion < param.ProfitProportion {
		Response(ctx)("分成大于上级", CodeError, false)(OK)
		return
	}

	Response(ctx)("",
		CodeSuccess,
		memberdao.NewMemberDao().UpdateWifiUser(userInfo.MemberId, userInfo.UserId, param.ProfitProportion, param.IsAdmin, param.IsDivinds).Unwrap())(OK)

}

// 扫码解绑 - 解绑设备wifi信息，设备与房间的绑定情况
func HandleScanUnbindDevice(ctx *gin.Context)  {
	var okPlace, okRoom bool
	memberId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	param := &struct {
		DeviceSn string  `json:"deviceSn"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param))

	// 设备是否为绑定状态
	deviceInfo := dao.NewDeviceDao().GetDeviceByDeviceSn(param.DeviceSn).Unwrap().(*devices.DeviceModel)
	roomInfo := dao.NewRoomDaoDao().GetRoomDetailsByDeviceSn(param.DeviceSn).Unwrap().(*room.Room)
	if deviceInfo.PlaceId == 0 && roomInfo.Id == 0 {
		Response(ctx)("设备未绑定", CodeSuccess, true)(OK)
		return
	}

	// 判断登录用户是否拥有权限
	if deviceInfo.PlaceId > 0 {
		userInfo := memberdao.NewMemberDao().GetWifiUserInfoByMemberId(memberId).Unwrap().(*users.WifiUserDetail)
		var placeIds []int
		//获取直属或下级网点Id
		userIdArr := dao.NewUserDao().QueryChildUserIds(userInfo.UserId).Unwrap().([]int)
		placeIdArr := dao.NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
		//合并网点
		placeIds = append(placeIds, placeIdArr...)
		//去重网点
		placesIds := utils.RemoveRepByMap(placeIds)
		if !helper.InSliceByInt(placesIds, deviceInfo.PlaceId) {
			Response(ctx)("解绑失败，没有权限", CodeSuccess, false)(OK)
			return
		}

		// 解绑门店
		okPlace = dao.NewDeviceDao().UnBindDevicePlaceByDeviceSn(param.DeviceSn).Unwrap().(bool)
	}

	if roomInfo.Id > 0 {
		okRoom = dao.NewRoomDaoDao().UnbindWifiInfoByDeviceSn(roomInfo.Id, param.DeviceSn).Unwrap().(bool)
	}

	if okPlace || okRoom {
		Response(ctx)("解绑成功", CodeSuccess, true)(OK)
		return
	}
	Response(ctx)("解绑失败", CodeSuccess, false)(OK)
}

// 提现列表
func HandleGetWifiUserCashList(ctx *gin.Context)  {
	param := &request.GetUserWifiListReq{}
	dingo.ErrorIf(ctx.Bind(param)).Unwrap()

	memberId, _ := helper.GetUserIdFromCtx(ctx)
	userInfo := memberdao.NewMemberDao().GetWifiUserInfoByMemberId(memberId).Unwrap().(*users.WifiUserDetail)
	param.UserId = userInfo.UserId
	param.IsAdmin = userInfo.IsAdmin

	data := dao.NewRoomDaoDao().GetUserRoomWifiList(param)
	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  0,
		Data:       data.Unwrap(),
	})(OK)
}
